import React, { useRef } from 'react';
import { Button } from 'antd-mobile';
import { AddOutline } from 'antd-mobile-icons';
import './index.css';

interface FileUploadProps {
  onFileSelect: (files: FileList) => void;
  disabled?: boolean;
  accept?: string;
  multiple?: boolean;
}

const FileUpload: React.FC<FileUploadProps> = ({
  onFileSelect,
  disabled = false,
  accept = "*/*",
  multiple = false
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      onFileSelect(files);
    }
    // 重置input值，允许重复选择同一文件
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleClick = () => {
    if (!disabled && fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  return (
    <div className="file-upload">
      <input
        ref={fileInputRef}
        type="file"
        accept={accept}
        multiple={multiple}
        onChange={handleFileChange}
        style={{ display: 'none' }}
        disabled={disabled}
      />
      <Button
        onClick={handleClick}
        disabled={disabled}
        className="upload-button"
        fill="outline"
        size="small"
      >
        <AddOutline />
        文件
      </Button>
    </div>
  );
};

export default FileUpload;

